<template>
    <view :style="{ '--color': color }">
        <!-- 通用版 -->
        <view class="mask" @click="cancel">
            <view class="model" v-if="modelType == 99">
                <view class="titleTip">{{ title }}</view>
                <view class="msgTip">{{ msg }}</view>
                <view class="btns">
                    <view class="btn-cancel" v-if="btn1" @click="cancel">{{ btn1 }}</view>
                    <view class="btn-cancel" v-if="btn3" @click="backHome">{{ btn3 }}</view>
                    <view class="btn-cancel" v-if="btn4" @click="other">{{ btn4 }}</view>
                    <view class="btn-yes thmeBg" @click="certain">{{ btn2 }}</view>
                </view>
            </view>
        </view>
        <Coupon v-if="CouponShow && couponArry" :couponArry="couponArry" @closeFunc="CouponShow = false"></Coupon>

        <u-popup :show="modelType == 2" round="10" :duration="200">
            <!-- 简约登录 -->
            <view class="fullModal d-flex f-column a-center" :style="{ '--total-height': totalHeight + 'px' }" v-if="startUp.rand_default == 2">
                <image :src="$imgUrls(startUp.logo_img)" mode="aspectFill" class="logo bor_radius_30"></image>
                <view class="size32 color_33 bold m-top40">{{ startUp.title }}</view>
                <view class="m-top100">
                    <button class="btn thmeBg flexac size30 white t-letter2" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" v-if="agree">授权手机号</button>
                    <view class="btn thmeBg flexac size30 white t-letter2" @click="Verify" v-else>授权手机号</view>
                    <view class="btn bgF2 flexac size30 color_33 t-letter2 m-top40" @click="cancel">取消</view>
                </view>
                <view class="flexac f-wrap m-top40 line40" :class="{ shake: shake }" v-if="agreementList.length" @click="agree = !agree">
                    <view class="agress flexac m-right20" :class="{ okAgress: agree }">
                        <view class="iconfont icon-xuanzhong h6 white"></view>
                    </view>
                    <text class="color_33">我已阅读并同意</text>
                    <text class="color" v-for="item in agreementList" :key="item.id" @click.stop="toDetails(item.id)">{{ item.title }}</text>
                </view>
            </view>

            <view class="ContentModel" v-else>
                <form @submit="Save">
                    <view class="Model">
                        <view class="headView m-bot30">
                            <view class="view_img">
                                <image :src="$imgUrls(headimg)" mode="aspectFill" class="headImg"></image>
                                <!-- <view class="camera ">切换</view> -->
                                <view class="iconfont icon-mn_shangchuantupian_fill size36 color_33 camera"></view>
                            </view>
                            <view class="size26 p-top14 text-center color_33">上传头像</view>
                            <button open-type="chooseAvatar" type="default" class="AvatarBtn" @chooseavatar="bindchooseavatar"></button>
                        </view>

                        <view class="list">
                            <text class="size28 color_33 bold500">昵称</text>
                            <view class="rightView d-flex">
                                <input type="nickname" name="nickname" v-model="nickName" class="rightVal p-left30 p-right20 size26 color_33" placeholder="请输入您的昵称" />
                                <view class="d-flex a-center color_66 p-right20" @click="RandomList">
                                    <view class="iconfont icon-suijishushengcheng size36"></view>
                                    <text class="size22 m-left10">更换</text>
                                </view>
                            </view>
                        </view>

                        <view class="row a-center m-top50 line40" :class="{ shake: shake }" v-if="agreementList.length">
                            <view class="agress flexac m-right20" :class="{ okAgress: agree }" @click.stop="agree = !agree">
                                <view class="iconfont icon-xiangxia white h7 m-top6"></view>
                            </view>
                            <text class="color_33 size22" @click.stop="agree = !agree">我已阅读并同意</text>
                            <text class="color size22" v-for="item in agreementList" :key="item.id" @click.stop="toDetails(item.id)">{{ item.title }}</text>
                        </view>

                        <view class="row j-sb m-top60">
                            <button class="login_btn bg33 flexac white size30 t-letter2" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" v-if="accredit">一键授权</button>
                            <button class="login_btn bg33 flexac white size30 t-letter2" form-type="submit" v-else>一键授权</button>

                            <view class="login_btn bgF2 flexac color_33 size30 t-letter2" @click.stop="cancel">取消</view>
                        </view>
                    </view>
                </form>
            </view>
        </u-popup>
    </view>
</template>

<script>
    import { mapState, mapMutations } from 'vuex';
    var that;
    import API from '../../api/index.js';
    import Coupon from '../Coupons.vue';
    export default {
        /**
         * goHome登录成功后是否返回首页  0不返回  1/null返回
         * btn1:取消按钮文字
         * btn2：确定按钮文字
         * btn3：返回首页文字
         * btn4：自定义
         * msg：提示文字
         * title: 标题
         * **/
        props: ['type', 'title', 'msg', 'goHome', 'btn1', 'btn2', 'btn3', 'btn4', 'btn1_url', 'btn2_url', 'jump'],
        data() {
            return {
                // color: getApp().globalData.color,
                modelType: this.type, // 弹窗类型

                userinfo: '',
                noAuth: null, // 用户未授权 true已授权 false未授权

                imgUrl: this.imgUrl,
                CouponShow: false,
                couponArry: '',

                headimg: '',
                nickName: '',
                Phone: '',
                agree: false,
                agreementList: [],
                shake: false
            };
        },
        components: {
            Coupon
        },
        watch: {
            type(e) {
                this.modelType = e;
            }
        },
        created() {
            if (!this.regInfo) return;
            this.agreements();
            // rand_default：0手动填写、1随机填写、2手机尾号+随机头像
            if (this.startUp.rand_default == 0) return;
            this.RandomList();
        },
        methods: {
            ...mapMutations(['getUser']),

            cancel() {
                //取消
                this.$emit('cancelFunc');
            },
            certain() {
                //确定
                this.$emit('certain');
            },
            other() {
                //自定义
                this.$emit('otherFunc');
            },
            async getPhoneNumber(e) {
                let result = e.detail;
                console.log(result, 'result');
                if (result.errMsg != 'getPhoneNumber:ok') return;
                const jscode = await this.getProvider();
                this.$showLoading('');
                this.$http
                    .post({
                        url: '/zzj_singleSaleApi/appletDecodePhone',
                        data: {
                            encryptedData: result.encryptedData,
                            iv: result.iv,
                            session_key: this.session_key,
                            js_code: jscode
                        }
                    })
                    .then((res) => {
                        this.$hideLoading();
                        if (res.code != 200) return this.$Toast(res.msg);
                        this.Phone = res.data;
                        if (this.startUp.rand_default == 2) {
                            let prefix = this.nameDefinition.namePrefix || '会员';
                            this.nickName = prefix + this.Phone.slice(-4);
                        }
                        this.Login();
                    });
            },

            async Login() {
                this.$showLoading('');
                const jscode = await this.getProvider();
                this.$http
                    .post({
                        url: '/zzj_singleSaleApi/appletLogin',
                        data: {
                            openid: this.openid,
                            nickName: this.nickName,
                            headimg: this.headimg,
                            purePhoneNumber: this.Phone,
                            share_v_id: this.share_v_id,
                            js_code: jscode
                        }
                    })
                    .then((res) => {
                        this.$hideLoading();
                        if (res.code != 200) return this.$Toast(res.msg);
                        let obj = {
                            vid: res.v_id,
                            userInfo: res.userInfo
                        };
                        uni.setStorageSync('vid', res.v_id);
                        this.getUser(obj);
                        this.cancel();
                        this.$emit('loginSucceed');
                        if (this.request.pid) this.bindRelation(res.v_id);
                        this.maintainLog(res.v_id);
                    });
            },

            bindchooseavatar(e) {
                let headimg = e.detail.avatarUrl;
                this.$common.uploadFiles(headimg).then((res) => {
                    if (res.errcode != '100') return this.$Toast('上传失败');
                    let imgs = res.url.substring(22);
                    this.headimg = imgs;
                });
            },

            async Save(e) {
                if (!this.headimg) return this.$Toast('头像不能为空!');
                if (!e.detail.value.nickname) return this.$Toast('昵称不能为空!');
                this.nickName = e.detail.value.nickname;
                if (!this.agree) {
                    this.$Toast('未同意协议');
                    this.shake = true;
                    setTimeout(() => {
                        this.shake = false;
                    }, 300);
                    return;
                }
                this.Login();
            },

            getProvider() {
                return new Promise((resolve, reject) => {
                    uni.getProvider({
                        service: 'oauth',
                        success: (res) => {
                            uni.login({
                                provider: res.provider[0],
                                success: (req) => {
                                    resolve(req.code);
                                }
                            });
                        }
                    });
                });
            },
            RandomList() {
                this.RandomArr(this.regInfo.imgList, 'headimg');
                if (this.startUp.rand_default == 2) return;
                this.RandomArr(this.regInfo.nicknameList, 'nickName');
            },
            RandomArr(array, name) {
                let randomIndex = Math.floor(Math.random() * array.length);
                name == 'headimg' ? (this.headimg = array[randomIndex]) : (this.nickName = array[randomIndex]);
            },

            agreements() {
                let agreeList = JSON.parse(JSON.stringify(this.regInfo.agreement));
                if (!agreeList.length) return;
                agreeList.forEach((item, index) => {
                    if (index != agreeList.length - 1) {
                        item.title = `《${item.title}》、`;
                    } else {
                        item.title = `《${item.title}》`;
                    }
                });
                this.agreementList = agreeList;
            },
            toDetails(id) {
                this.toUrl(`/otherPage/article/artDetail?artId=${id}`);
            },
            bindRelation(vid) {
                // 私域-绑定会员关系
                this.$http
                    .post({
                        url: '/PrivateSphereApi/bindPrivateRelation',
                        data: {
                            vid,
                            pid: this.request.pid,
                            way: this.request.w || 1
                        }
                    })
                    .then((res) => {
                        console.log(res);
                    });
            },
            maintainLog(v_id) {
                // 维护口令使用记录
                let used_log_id = uni.getStorageSync('used_log_id');
                if (!used_log_id || used_log_id == 0) return;
                this.$http
                    .post({
                        url: '/automaticTask/upDateUsedLog',
                        data: {
                            v_id,
                            used_log_id
                        }
                    })
                    .then((res) => {
                        uni.removeStorageSync('used_log_id');
                    });
            },
            Verify() {
                this.$Toast('未同意协议');
                this.shake = true;
                setTimeout(() => {
                    this.shake = false;
                }, 300);
            }
        },

        computed: {
            ...mapState(['openid', 'session_key', 'bid', 'share_v_id', 'color', 'regInfo', 'request', 'startUp', 'totalHeight', 'nameDefinition']),
            accredit() {
                if (this.headimg && this.nickName && this.agree) {
                    return true;
                } else {
                    return false;
                }
            }
        },

        watch: {
            agreementList: {
                deep: true,
                immediate: true,
                handler(newVal, oldVal) {
                    newVal.length ? (this.agree = false) : (this.agree = true);
                }
            }
        }
    };
</script>

<style scoped lang="scss">
    .shake {
        animation: shake 0.3s;
    }
    @keyframes shake {
        0% {
            transform: translateX(0);
        }
        25% {
            transform: translateX(-10rpx);
        }
        50% {
            transform: translateX(10rpx);
        }
        75% {
            transform: translateX(-10rpx);
        }
        100% {
            transform: translateX(0);
        }
    }
    .ContentModel {
        width: 100%;
        padding-bottom: constant(safe-area-inset-bottom);
        /*兼容 IOS<11.2*/
        padding-bottom: env(safe-area-inset-bottom);
        /*兼容 IOS>11.2*/
    }

    .Model {
        width: 100%;
        padding: 50rpx 50rpx 140rpx 50rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
    }

    .headView {
        position: relative;
        padding: 10rpx 20rpx;
    }

    .headImg,
    .view_img {
        width: 140rpx;
        height: 140rpx;
        border-radius: 50%;
    }

    .view_img {
        box-shadow: 0 0 20rpx rgba(151, 151, 151, 0.3);
        position: relative;
    }

    .camera {
        position: absolute;
        right: 0rpx;
        bottom: 10rpx;
    }

    .AvatarBtn {
        position: absolute;
        width: 100%;
        height: 100%;
        left: 0;
        top: 0;
        z-index: 10;
        background-color: transparent;
    }

    .AvatarBtn::after {
        border: none;
    }

    .list {
        width: 100%;
        margin-top: 30rpx;
        display: flex;
        align-items: center;
    }

    .rightView {
        flex: 1;
        height: 80rpx;
        margin-left: 40rpx;
        background-color: #f2f2f2;
        border-radius: 40rpx;
        overflow: hidden;
    }
    .rightVal {
        flex: 1;
        height: 100%;
        background-color: #f2f2f2;
    }

    .login_btn {
        width: 310rpx;
        height: 90rpx;
        padding: 0;
        margin: 0 0 30rpx 0;
        border-radius: 45rpx;
    }

    .agress {
        width: 28rpx;
        height: 28rpx;
        border: 1px solid #dedede;
        border-radius: 50%;
    }
    .okAgress {
        border: 1px solid var(--color);
        background-color: var(--color);
    }
    .icon-xiangxia {
        zoom: 0.8;
    }

    .model {
        position: fixed;
        width: 654rpx;
        /* height: 320rpx; */
        left: 50%;
        top: 50%;
        border-radius: 32rpx;
        transform: translate(-50%, -50%);
        background: white;
        overflow: hidden;
        z-index: 999;
    }

    .titleTip {
        font-size: 36rpx;
        height: 111rpx;
        line-height: 160rpx;
        font-weight: bold;
        text-align: center;
    }

    .msgTip {
        font-size: 28rpx;
        color: #999999;
        text-align: center;
        padding: 30rpx 66rpx;
    }

    .btns {
        display: flex;
        justify-content: center;
        padding: 50rpx;
    }

    .btn-cancel {
        width: 260rpx;
        font-size: 30rpx;
        text-align: center;
        color: #969696;
        border: 1px solid #afafaf;
        border-radius: 68rpx;
        line-height: 68rpx;
        background: none;
        margin: 0 10rpx;
    }

    .btn-yes {
        width: 260rpx;
        font-size: 30rpx;
        color: white;
        text-align: center;
        border-radius: 68rpx;
        line-height: 68rpx;
        margin: 0 10rpx;
    }

    .mask {
        display: flex;
        align-items: center;
        justify-content: center;

        .model {
            background-color: #ffffff;
            border-radius: 12rpx;
            width: 600rpx;
            text-align: center;
            overflow: hidden;
            padding-top: 20rpx;
        }
    }
    .fullModal {
        height: 100vh;
        padding: calc(100rpx + var(--total-height)) 50rpx 0 50rpx;
        .logo {
            width: 180rpx;
            height: 180rpx;
        }
        .btn {
            width: 600rpx;
            height: 90rpx;
            border-radius: 45rpx;
        }
    }
</style>
